var util = require('util');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Promise = require('promise');
var options = {//连接池设置
    server: {
        auto_reconnect: true,
        poolSize: 5
    }
};
var dburl = require('../config').dbUrl;//数据库地址

var connect = function(){
    mongoose.connect(dburl, options, function(err, res) {
        if(err) {
            console.log('[mongoose log] Error connecting to: ' + dburl + '. ' + err);
            require('../config').setError(err, 500);
        } else {
            console.log('[mongoose log] Successfully connected to: ' + dburl);
        }});
};

module.exports = {
    openDB: function(){
        connect();
        var db = mongoose.connection;
        db.on('error', console.error.bind(console, 'mongoose connection error:'));
        db.once('open', function callback () {
            // yay!
            console.log('mongoose open success');
        });
        //定义数据库Schema
        require('./model').initModel(db, Schema);

    },
    disconnect: function(){
        mongoose.disconnect();
    },
    PromiseDao: {
        find: function(Model, fields, argsObj, whereArr){
            if(!fields.push){
                whereArr = argsObj;
                argsObj = fields;
            }
            if(typeof argsObj === 'function'){
                whereArr = argsObj;
            }
            return new Promise(function (resolve, reject) {
                var query = fields.push ? Model.find(fields, argsObj || {}) : Model.find(argsObj || {});
                (whereArr || []).forEach(function(n){
                    if(query[n.key]){
                        query[n.key].call(query, n.value);
                    }
                });
                query.exec(function (err, doc) {
                    if (err) {
                        console.log(err);
                        reject(err.message);
                    } else {
                        resolve(doc);
                    }
                });
            });

        },
        findOne: function (Model, argsObj) {
            return new Promise(function (resolve, reject) {
                Model.findOne(argsObj, function (err, doc) {
                    if (err) {
                        console.log(err);
                        reject(err.message);
                    } else {
                        resolve(doc);
                    }
                });
            });
        },
        /**
         * 如果是Entity，使用save方法，如果是Model，使用create方法
         * @param Model
         * @param obj 使用Model新增时，传入的对象只能是纯净的JSON对象，不能是由Model创建的实体
         */
        create: function(Model, entity){
            return new Promise(function (resolve, reject) {
                Model.create(entity, function(err, doc){
                    if (err) {
                        console.log(err);
                        reject(err.message);
                    } else {
                        resolve(doc);
                    }
                });
            });
        },
        save: function(Entity){
            return new Promise(function (resolve, reject) {
                Entity.save(function(err, doc){
                    if (err) {
                        console.log(err);
                        reject(err.message);
                    } else {
                        resolve(doc);
                    }
                });
            });
        }
    }
};
